package certs

import (
	"crypto/tls"
	"crypto/x509"
	"go_template/log"
	"io/ioutil"
	"os"
)

var (
	CertKeyPairs *tls.Certificate
	Certpool     *x509.CertPool
)

func loadAllCerts() ([]byte, []byte) {
	defer func() {
		log.ShowLogger.Info("加载服务器认证信息文件 完成")
	}()
	var (
		keyBuffer, pemBuffer []byte
		err                  error
		cwd                  string
	)

	cwd, err = os.Getwd()
	if err != nil {
		panic(err)
	}
	log.ShowLogger.Info("加载服务器认证信息文件...")
	cwd += "/certs/"
	keyBuffer, err = ioutil.ReadFile(cwd + "server.key")
	if err != nil {
		panic(err)
	}

	pemBuffer, err = ioutil.ReadFile(cwd + "server.pem")
	if err != nil {
		panic(err)
	}

	return pemBuffer, keyBuffer
}

func init() {
	var err error
	cert, key := loadAllCerts()
	pair, err := tls.X509KeyPair([]byte(cert), []byte(key))
	if err != nil {
		panic(err)
	}
	CertKeyPairs = &pair
	Certpool = x509.NewCertPool()
	ok := Certpool.AppendCertsFromPEM([]byte(cert))
	if !ok {
		panic("load fail certs")
	}
}
